package com.pu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pu.constant.MessageConstant;
import com.pu.constant.PasswordConstant;
import com.pu.constant.StatusConstant;
import com.pu.context.BaseContext;
import com.pu.dto.EmployeeDTO;
import com.pu.dto.EmployeeLoginDTO;
import com.pu.dto.EmployeePageQueryDTO;
import com.pu.dto.PasswordEditDTO;
import com.pu.entity.Employee;
import com.pu.exception.AccountNotFoundException;
import com.pu.exception.PasswordErrorException;
import com.pu.mapper.EmployeeMapper;
import com.pu.result.PageResult;
import com.pu.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.pu.exception.AccountLockedException;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: Yusc
 * @Date: 2023/10/22 17:12
 * @Version:
 * @Description: 员工管理业务层
 **/
@Service
@Slf4j
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * @param employeeLoginDTO
     * @auther: Yusc
     * @date: 2023/10/22 17:13
     * @Description: 员工登录
     */
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = lambdaQuery().eq(Employee::getUsername, username).one();
        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //密码比对
        // 对前端传过来的密码进行md5加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        //3、返回实体对象
        return employee;

    }

    /**
     * @auther: Yusc
     * @date: 2023/10/25 16:04
     * @Description: 新增员工
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();

        //对象属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);

        //设置账号的状态，默认正常状态 1表示正常 0表示锁定
        employee.setStatus(StatusConstant.ENABLE);

        //设置密码，默认密码123456   用md5加密在存到数据库
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        //设置当前记录的创建时间和修改时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        // 设置当前记录创建人id和修改人id
        // 动态获取当前用户的id
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());

        if (save(employee)) {
            log.info("新增员工成功!:{}", employee);
        }
    }

    /**
     * @param employeePageQueryDTO
     * @auther: Yusc
     * @date: 2023/10/25 17:16
     * @Description: 员工分页条件查询
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //开始分页查询
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        // 进行分页查询
        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);

        // 需要返回给前端的数据
        long total = page.getTotal();   // 总记录数
        List<Employee> records = page.getResult();  // 当前页数据集合

        return new PageResult(total, records);
    }

    /**
     * @param status
     * @param id
     * @auther: Yusc
     * @date: 2023/10/25 23:22
     * @Description: 启用禁用员工账号
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        Employee employee = new Employee();
        employee.setId(id);
        employee.setStatus(status);

        // 1.构建查询条件
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<Employee>()
                .eq(Employee::getId, id);

        // 2.更新数据，user中非null字段都会作为set语句
        update(employee, wrapper);

    }

    /**
     * @param employeeDTO
     * @return
     * @auther: Yusc
     * @date 2023/10/26 16:32
     * @Description 编辑更新员工信息
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee); //属性拷贝

        employee.setUpdateTime(LocalDateTime.now());        //更新修改时间
        employee.setUpdateUser(BaseContext.getCurrentId()); //更新修改人id

        // 1.构建查询条件
        boolean update = lambdaUpdate()
                .eq(Employee::getId, employee.getId())
                .update(employee);

        if (update) {
            log.info("更新成功！更新人:{},更新时间:{}", employee.getUpdateUser(), employee.getUpdateTime());
        }
    }

    /**
     * @auther: Yusc
     * @date 2023/11/5 18:02
     * @Description 修改密码
     */
    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        //获取当前登录用户的id
        Long empId = BaseContext.getCurrentId();
        //就可以查到数据库的用户信息
        Employee employee = employeeMapper.selectById(empId);
        //当前 前端传过来的oldPassword进行md5加密后
        String pwd = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());
        //进行对比
        if (!pwd.equals(employee.getPassword())) {
            //原密码错误
            throw new PasswordErrorException("原密码错误");
        }
        //如果输入的原密码与数据库密码相同，则进行修改，把newPassword进行MD5加密存入数据库，密码修改成功
        employee.setPassword(DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes()));
        employee.setUpdateUser(empId);
        employee.setUpdateTime(LocalDateTime.now());
        employeeMapper.updateById(employee);


    }

}
